const fs = require('fs')
const path = require('path')
const utils = require('./build/utils')
const webpack = require('webpack')
const vueLoaderConfig = require('./build/vue-loader.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
// const ExtractTextPlugin = require('extract-text-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const pagesDirPath = './src/pages'
const entry = {}
let pages = []
const fileNames = findSync(pagesDirPath)
pages = fileNames.map(function (item) {
  return item.split(`src\\pages\\`)[1].replace('.js', '')
})

// 设置绝对路径
function resolve (dir) {
  return path.join(__dirname, dir)
}

function entryFilePath (key) {
  return `${pagesDirPath}/${key}.js`
}

pages.map(function (item) {
  entry[item] = entryFilePath(item)
})
const config = {
  output: {
    path: resolve('pages/static'),
    filename: 'js/[name].[chunkhash].js',
    chunkFilename: 'js/[id].[chunkhash].js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [
          resolve('src'),
          resolve('test'),
          resolve('node_modules/webpack-dev-server/client')
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.sass$/,
        loaders: ['style', 'css', 'sass']
      }
    ]
  },
  plugins: [
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks (module) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, 'node_modules')
          ) === 0
        )
      }
    }),
    // copy custom static assets, like style files or iamges
    new CopyWebpackPlugin([
      {
        from: resolve('static'),
        to: resolve('pages/static'),
        ignore: ['.*', '*.scss']
      }
    ])
  ]
}
config.entry = entry
pages.map(function (item) {
  config.plugins.push(new HtmlWebpackPlugin({
    filename: resolve(`pages/${item}.html`),
    template: 'page.html',
    inject: true,
    minify: {
      removeComments: true,
      collapseWhitespace: true,
      removeAttributeQuotes: true
      // more options:
      // https://github.com/kangax/html-minifier#options-quick-reference
    },
    // necessary to consistently work with multiple chunks via CommonsChunkPlugin
    chunksSortMode: 'dependency',
    chunks: ['vendor', item]
  }))
})

// 读取文件夹下的文件名
function findSync(startPath) {
  let result=[];
  function finder(_path) {
    let files = fs.readdirSync(_path);
    files.forEach((val,index) => {
      let fPath = path.join(_path,val);
      let stats = fs.statSync(fPath);
      if(stats.isDirectory()) finder(fPath);
      if(stats.isFile()) result.push(fPath);
    });
  }
  finder(startPath);
  return result;
}

module.exports = config
